package com.demo.controller;

import com.alibaba.fastjson.JSON;
import com.demo.model.entity.User;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * apisix控制器
 */
@Slf4j
@RestController
public class ApisixController {

    @Value("${server.port}")
    String port;

    /**
     * 健康检查
     */
    @GetMapping("/healthy")
    public String healthy() {
        log.info("port:{} health", port);
        return "port:" + port;
    }

    /**
     * apisxix外部服务器校验请求是否合法
     * @param authorization 请求头参数
     * @return 返回response code和信息
     */
    @PostMapping("/auth")
    public ResponseEntity<String> auth(@RequestHeader("authorization") String authorization, @RequestBody User user) {
        log.info("header:{},param:{}", authorization, JSON.toJSONString(user));
        if (StringUtils.equals(authorization, "123") && StringUtils.equals(user.getUserName(), "123")) {
            return ResponseEntity.accepted().body("通过");
        }

        return ResponseEntity.status(HttpStatus.FORBIDDEN).body("禁止");
    }

    /**
     * 通过apisix外部服务器校验通过之后，转发的请求
     * @param authorization 请求头参数
     * @return 返回报文
     */
    @PostMapping("/isPass")
    public String isPass(@RequestHeader("authorization") String authorization, @RequestBody User user) {
        HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        String modify = req.getHeader("modify");
        log.info("modify:{}", modify);

        log.info("header:{},param:{}", authorization, JSON.toJSONString(user));
        return "请求参数校验通过，参数：" + JSON.toJSONString(user);
    }

    /**
     * 不需要外部服务器校验，直接转发本接口
     * @param authorization 请求头
     * @param user 请求体
     * @return 返回报文
     */
    @PostMapping("/throughAuth")
    public String throughAuth(@RequestHeader("authorization") String authorization, @RequestBody User user) {
        log.info("header:{},param:{}", authorization, JSON.toJSONString(user));
        return "穿透校验通过";
    }
}
